package com.beagle.njddapp.ui.presenter;

import com.beagle.njddapp.base.ApiService;
import com.beagle.njddapp.base.BaseApplication;
import com.beagle.njddapp.base.BasePresenter;
import com.beagle.njddapp.base.NjOwnerApiService;
import com.beagle.njddapp.base.OilApiService;
import com.beagle.njddapp.base.RetrofitHttp;
import com.beagle.njddapp.bean.JszBean;
import com.beagle.njddapp.bean.OcrIdBean;
import com.beagle.njddapp.bean.OcrIdPhotoBean;
import com.beagle.njddapp.bean.UploadBean;
import com.beagle.njddapp.bean.UserInfoBean;
import com.beagle.njddapp.bean.oil.OilBean;
import com.beagle.njddapp.bean.owner.DIrverOrderBean;
import com.beagle.njddapp.core.UserService;
import com.beagle.njddapp.net.BaseHttpResponse;
import com.beagle.njddapp.net.BaseOilHttpListResponse;
import com.beagle.njddapp.net.BaseOilHttpResponse;
import com.beagle.njddapp.net.HttpResponseObserver;
import com.beagle.njddapp.net.RxSchedulers;
import com.beagle.njddapp.ui.view.BasicUserInfoView;
import com.beagle.njddapp.utils.Utils;
import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.beagle.njddapp.core.UserService.ROLE_OIL;
import static com.beagle.njddapp.core.UserService.ROLE_OWNER;

/**
 * @author hxx
 * @date 2021-03-02 22:33
 */
public class BasicUserInfoPresenter extends BasePresenter<BasicUserInfoView> {
    private ApiService apiService;
    private NjOwnerApiService njOwnerApiService;
    private OilApiService OilapiService;
    public BasicUserInfoPresenter() {
        retrofit2.Retrofit retrofit = RetrofitHttp.provideRetrofit();
        //获取接口对象
        apiService = retrofit.create(ApiService.class);
        njOwnerApiService = retrofit.create(NjOwnerApiService.class);
        OilapiService = retrofit.create(OilApiService.class);
    }

    public void information(UserInfoBean userInfoBean) {
        Gson gson=new Gson();
        String strEntity = gson.toJson(userInfoBean);
        RequestBody body =RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);
        apiService.information(body).compose(RxSchedulers.compose()).subscribe(new HttpResponseObserver<BaseHttpResponse>() {


            @Override
            public void success(BaseHttpResponse baseHttpResponse) {
                getUserInfo();
            }

            @Override
            public void error(int code, String message) {
                getView().onError(message);

            }
        });
    }
    public void ocrCardNumber(String number,String name){
        String url="https://lfeid.market.alicloudapi.com/idcheck/life";
        apiService.ocrIdCard(url,number,name).
                compose(RxSchedulers.compose()).safeSubscribe(new Observer<OcrIdBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OcrIdBean ocrIdCardBean) {
                if (ocrIdCardBean!=null){
                    getView().showIdInfo(ocrIdCardBean);
                }else {
                    getView().onError("网络异常");
                }

            }

            @Override
            public void onError(Throwable e) {
                getView().onError("网络异常");
            }

            @Override
            public void onComplete() {

            }
        });
    }

    public void getUserInfo() {
        apiService.getUserInfo().compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseHttpResponse<UserInfoBean>>() {

            @Override
            public void success(BaseHttpResponse<UserInfoBean> userInfoBeanBaseHttpResponse) {
                if (userInfoBeanBaseHttpResponse!=null&&userInfoBeanBaseHttpResponse.data!=null){
                    UserService.getInstance().setUserInfoBean(userInfoBeanBaseHttpResponse.data);
                    if (userInfoBeanBaseHttpResponse.data.getUserRole()==0){
                        getView().toRole();
                    }else {
                        getView().toMian();
                    }

                }else {
                    getView().onError("请重试");
                }
            }

            @Override
            public void error(int code, String message) {
                getView().onError(message);

            }
        });
    }
    public void queryUserInfo(UserInfoBean userInfoBean) {
        apiService.queryInvateCode(userInfoBean.getInvitationCode()).compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseHttpResponse<UserInfoBean>>() {

            @Override
            public void success(BaseHttpResponse<UserInfoBean> userInfoBeanBaseHttpResponse) {
                if (userInfoBeanBaseHttpResponse!=null&&userInfoBeanBaseHttpResponse.data!=null){
                    information(userInfoBean);
                }else {
                    getView().onError("为查询到相关邀请人信息，请重新输入邀请码");
                }
            }

            @Override
            public void error(int code, String message) {
                getView().onError(message);

            }
        });
    }


    public void upload(String path){

        Luban.with(BaseApplication.getInstance().getApplicationContext())
                .load(path)// 传人要压缩的图片列表
                .ignoreBy(1000)
                .setTargetDir(BaseApplication.getInstance().getCacheDir().getAbsolutePath())                        // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        String name=path.substring(path.lastIndexOf("/")+1,path.length()-1);
                        LogUtils.d(name);
                        RequestBody body=RequestBody.create(MediaType.parse("multipart/form-data"),file);//表单类型
                        MultipartBody.Builder builder = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM);
                        builder.addFormDataPart("file",file.getName(),body); //添加图片数据，body创建的请求体
                        List<MultipartBody.Part> parts=builder.build().parts();
                        apiService.uploadFile(parts).compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseHttpResponse<UploadBean>>() {
                            @Override
                            public void success(BaseHttpResponse<UploadBean> uploadBeanBaseHttpResponse) {
                                if (uploadBeanBaseHttpResponse.data != null) {
                                    getView().UploadSuccess(uploadBeanBaseHttpResponse.data);
                                } else {
                                    getView().onError("请重试");
                                }
                            }

                            @Override
                            public void error(int code, String message) {
                                getView().onError(message);
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();

    }

    public void firstRequest() {
        if (UserService.getInstance().getRole()==ROLE_OWNER){
            Gson gson=new Gson();
            HashMap<String,String> paramsMap=new LinkedHashMap<>();
            String strEntity = gson.toJson(paramsMap);
            RequestBody body =RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);
            paramsMap.clear();
            njOwnerApiService.getDeviceList(1000+"",1+"",body).compose(RxSchedulers.compose()).subscribe(new HttpResponseObserver<BaseOilHttpListResponse>() {


                @Override
                public void success(BaseOilHttpListResponse baseOilHttpListResponse) {
                    getView().toMian();
                }

                @Override
                public void error(int code, String message) {
                    getView().toMian();

                }
            });
        }else if (UserService.getInstance().getRole()==ROLE_OIL){
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),"{}");
            OilapiService.myCard(body).compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseOilHttpResponse<OilBean>>() {
                @Override
                public void success(BaseOilHttpResponse<OilBean> oilHttpResponse) {
                    getView().toMian();

                }

                @Override
                public void error(int code, String message) {
                    getView().toMian();
                }
            });
        }else {
            Gson gson = new Gson();
            HashMap<String, String> paramsMap = new LinkedHashMap<>();
            paramsMap.put("orderId", "");
            paramsMap.put("orderNum", "");
            paramsMap.put("orderStatus", "");
            String strEntity = gson.toJson(paramsMap);
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
            paramsMap.clear();
            njOwnerApiService.queryFindDriverOrderList(1000 + "", 1 + "", body).compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseOilHttpListResponse<DIrverOrderBean>>() {
                @Override
                public void success(BaseOilHttpListResponse<DIrverOrderBean> orderBeanBaseOilHttpListResponse) {
                    getView().toMian();
                }

                @Override
                public void error(int code, String message) {
                    getView().toMian();
                }
            });
        }
    }
    public void ocr(String filepath){
        String url="https://lfeid.market.alicloudapi.com/thirdnode/ImageAI/idcardfrontrecongnition";
        Luban.with(BaseApplication.getInstance().getApplicationContext())
                .load(filepath)// 传人要压缩的图片列表
                .ignoreBy(1400)                                  // 忽略不压缩图片的大小
                .setTargetDir(BaseApplication.getInstance().getCacheDir().getAbsolutePath())                        // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }
                    @Override
                    public void onSuccess(File file) {
                        apiService.ocr(url,Utils.pictureToBase64(file.getAbsolutePath())).
                                compose(RxSchedulers.compose()).safeSubscribe(new Observer<OcrIdPhotoBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(OcrIdPhotoBean ocrIdCardBean) {
                                if (ocrIdCardBean!=null){
                                    getView().showIdCard(ocrIdCardBean);
                                }else {
                                    getView().onError("网络异常");
                                }

                            }

                            @Override
                            public void onError(Throwable e) {
                                getView().onError("网络异常");
                            }

                            @Override
                            public void onComplete() {

                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();

    }
    public void ocrJsz(String filepath,String side){
        String url="https://dm-52.data.aliyun.com/rest/160601/ocr/ocr_driver_license.json";
        Luban.with(BaseApplication.getInstance().getApplicationContext())
                .load(filepath)// 传人要压缩的图片列表
                .ignoreBy(1400)                                  // 忽略不压缩图片的大小
                .setTargetDir(BaseApplication.getInstance().getCacheDir().getAbsolutePath())                        // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }
                    @Override
                    public void onSuccess(File file) {
//                        JSONObject configObj = new JSONObject();
//                        try {
//                            configObj.put("side", side);
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                        String config_str = configObj.toString();

                        Gson gson=new Gson();
                        HashMap<String,String> paramsMap=new HashMap<>();
                        paramsMap.put("image", Utils.pictureToBase64(file.getAbsolutePath()));
                        paramsMap.put("configure", "\"side\":\""+side+"\"");
                        String strEntity = gson.toJson(paramsMap);
                        RequestBody body =RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);
                        apiService.ocrJsz(url,body).
                                compose(RxSchedulers.compose()).safeSubscribe(new Observer<JszBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(JszBean jszBean) {
                                getView().showJszSuccess(file.getAbsolutePath());

                            }

                            @Override
                            public void onError(Throwable e) {
                                if ("face".equals(side)){
                                    getView().onError("请上传真实的驾驶证正面照片");
                                }else {
                                    getView().onError("请上传真实的驾驶证副页照片");
                                }
                            }

                            @Override
                            public void onComplete() {

                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();

    }
    public static JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }


}
